package com.yunchuang.controller.fileinfo;

import com.yunchuang.utils.ProfileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

@WebServlet("/uploadFiles")
// 支持文件上传
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    private final Logger logger= LoggerFactory.getLogger("logback");
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理POST请求的逻辑
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        Collection<Part> parts = req.getParts();
        // 获取IP地址
        for (Part part : parts) {
            // 文件上传时候的名称
            String fileName = part.getSubmittedFileName();
            String upload = ProfileUtils.getServerContext() + File.separator + fileName;
            File file = new File(upload);
            // 判断上传的父级目录是否存在
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                // 将文件写到指定文件中
                part.write(upload);
                logger.info(fileName + "上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                logger.info("保存失败");
            }
        }
    }
}